package com.example.administrator.zhongyichou.activity;

import android.Manifest;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.example.administrator.zhongyichou.Bean.BaseEventBean;
import com.example.administrator.zhongyichou.Bean.ChoiceBean;
import com.example.administrator.zhongyichou.Bean.SupplyDiseaseBean;
import com.example.administrator.zhongyichou.adapter.ReplenishmentGridAdapter;
import com.example.administrator.zhongyichou.base.BaseActivity;
import com.example.administrator.zhongyichou.base.MyApplication;
import com.example.administrator.zhongyichou.config.Constants;
import com.example.administrator.zhongyichou.net.NetConfig;
import com.example.administrator.zhongyichou.net.core.UploadHttpLoader;
import com.example.administrator.zhongyichou.net.presentor.SupplyDiseaseProtocol;
import com.example.administrator.zhongyichou.net.protocol.GsonBaseProtocol;
import com.example.administrator.zhongyichou.utils.FileUtils;
import com.example.administrator.zhongyichou.utils.ImageUtils;
import com.example.administrator.zhongyichou.utils.ToastUtil;
import com.example.administrator.zhongyichou.view.ChoiceDialog;
import com.example.administrator.zhongyichou.view.HeaderView;
import com.example.administrator.zhongyichou.view.LoadingDialog;
import com.example.administrator.zhongyichou.view.MyGridView;
import com.example.administrator.zhongyichou.net.core.HttpLoader;
import com.example.administrator.zhongyichou.net.listener.ResultListener;
import com.example.administrator.zhongyichou.R;
import com.lzy.ninegrid.ImageInfo;
import com.lzy.ninegrid.preview.ImagePreviewActivity;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import me.nereo.multi_image_selector.MultiImageSelector;

/**
 * Created by lichenyu on 2017/11/21.
 * 描述：补充大病资料
 */

public class ReplenishmentDiseaseInformationActivity extends BaseActivity implements AdapterView.OnItemClickListener, ReplenishmentGridAdapter.OnClickListener, ChoiceDialog.OnClik, ResultListener<SupplyDiseaseProtocol> {
    @BindView(R.id.headerview)
    HeaderView headerview;
    @BindView(R.id.ll_choose_prove)
    LinearLayout llChooseProve;
    @BindView(R.id.gridview)
    MyGridView gridview;
    @BindView(R.id.btn_next)
    Button btnNext;
    @BindView(R.id.edit_name)
    EditText editName;
    @BindView(R.id.radio_group)
    RadioGroup radioGroup;
    @BindView(R.id.radio_01)
    RadioButton radio01;
    @BindView(R.id.radio_02)
    RadioButton radio02;
    @BindView(R.id.txt_prove)
    TextView txtProve;
    @BindView(R.id.edit_prove)
    EditText editProve;
    @BindView(R.id.edit_disease)
    EditText editDisease;
    @BindView(R.id.edit_address)
    EditText editAddress;
    @BindView(R.id.edit_hospital_name)
    EditText editHospitalName;
    @BindView(R.id.txt_choose_prove)
    TextView txtChooseProve;

    private int REQUEST_IMAGE = 10;
    private ArrayList<String> listPhoto = new ArrayList<>();
    private ReplenishmentGridAdapter adapter;
    private int urllI = R.mipmap.zhengduan;//例子图片
    private String infoID;
    private List<ChoiceBean> choiceBeanList;
    private ChoiceDialog choiceDialog;
    private int proveYype = 0;
    private int idcType = 1;
    private LoadingDialog dialog;
    //此参数判断从那个界面跳转过来，0正常步骤，1补充资料，2编辑资料
    private int intentType = 0;

    @Override
    protected void init() {
        ButterKnife.bind(this);
        initHead();
        intentType = getIntent().getIntExtra("intentType", 0);
        infoID = getIntent().getStringExtra("info_id");
        initGrid();
        initChoice();
        initRadio();
        initDialog();
    }

    private void initDialog() {
        dialog = new LoadingDialog(this);
        dialog.setText("正在提交");
    }

    private void initRadio() {
        radio02.setChecked(true);
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == radio01.getId()) {//身份证
                    idcType = 0;
                    txtProve.setText("身份证");
                    editProve.setHint("请输入身份证号码");
                } else {//出生证明
                    idcType = 1;
                    txtProve.setText("出生证明编号");
                    editProve.setHint("请输入患者出生证编号");
                }
            }
        });
    }

    private void initGrid() {
        adapter = new ReplenishmentGridAdapter(this, listPhoto, urllI);
        gridview.setAdapter(adapter);
        gridview.setOnItemClickListener(this);
        adapter.setOnClick(this);
    }

    private void initChoice() {
        choiceDialog = new ChoiceDialog(this);
        choiceBeanList = new ArrayList<>();
        ChoiceBean choiceBean = new ChoiceBean();
        choiceBean.name = "诊断证明";
        choiceBean.isSelect = true;
        choiceBeanList.add(choiceBean);
        ChoiceBean choiceBean1 = new ChoiceBean();
        choiceBean1.name = "入院病案首页";
        choiceBeanList.add(choiceBean1);
        ChoiceBean choiceBean2 = new ChoiceBean();
        choiceBean2.name = "出院小结";
        choiceBeanList.add(choiceBean2);
        ChoiceBean choiceBean3 = new ChoiceBean();
        choiceBean3.name = "病情说明书";
        choiceBeanList.add(choiceBean3);
        choiceDialog.setData(choiceBeanList);
        choiceDialog.setOnClik(this);
    }

    @Override
    protected void responseData(GsonBaseProtocol mGsonBaseProtocal) {

    }

    @Override
    protected HttpLoader initHttpLoader() {
        return null;
    }

    @Override
    protected int initContentView() {
        return R.layout.replenishment_disease_information_activity;
    }

    @Override
    public boolean onEventBus(BaseEventBean baseEventBean) {

        return false;
    }

    @OnClick({R.id.ll_choose_prove, R.id.btn_next})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_choose_prove://选择资料
                choiceDialog.show();
                break;
            case R.id.btn_next://下一步
                supply();
                break;
        }
    }

    /**
     * 补充资料
     */
    private void supply() {
        final String realName = editName.getText().toString().trim();
        if (realName.length() == 0) {
            ToastUtil.showToast("请输入姓名");
            return;
        }
        final String idcNum = editProve.getText().toString().trim();
        if (idcNum.length() == 0) {
            ToastUtil.showToast("请输入证明编号");
            return;
        }
        final String diseaseName = editDisease.getText().toString().trim();
        if (diseaseName.length() == 0) {
            ToastUtil.showToast("请输入所患疾病");
            return;
        }
        final String hospitalAdd = editAddress.getText().toString().trim();
        if (hospitalAdd.length() == 0) {
            ToastUtil.showToast("请输入医院地址");
            return;
        }
        final String hospitalName = editHospitalName.getText().toString().trim();
        if (hospitalName.length() == 0) {
            ToastUtil.showToast("请输入医院名称");
            return;
        }
        if (listPhoto.size() == 0) {
            ToastUtil.showToast("请选择资料图片");
            return;
        }
        dialog.show();
        new Thread(new Runnable() {
            @Override
            public void run() {
                final List<File> listFile = ImageUtils.compressImages(listPhoto);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        UploadHttpLoader requestHttpLoader = new UploadHttpLoader(SupplyDiseaseProtocol.class);
                        Map<String, String> map = new HashMap<>();
                        map.put("user_id", MyApplication.getUserID());
                        map.put("info_id", infoID);
                        map.put("real_name", realName);
                        map.put("idc_type", idcType + "");
                        map.put("idc_num", idcNum);
                        map.put("disease_name", diseaseName);
                        map.put("hospital_name", hospitalName);
                        map.put("hospital_add", hospitalAdd);
                        map.put("prove_type", proveYype + "");
                        requestHttpLoader.setParams(NetConfig.SUPPLY_DISEASE, listFile, map, "prove_img");
                        requestHttpLoader.executor(ReplenishmentDiseaseInformationActivity.this);
                    }
                });
            }
        }).start();
    }

    private void initHead() {
        headerview.setTitle("资料证明");
        headerview.bindOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case HeaderView.LEFT:
                        finish();
                        break;
                }
            }
        });
    }

    //获取权限
    private void getPermissions() {
        new RxPermissions(this).request(Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Boolean value) {
                        if (value) {//如果所有权限都通过
                            startCamra();
                        } else {
                            getPermissions();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    private void startCamra() {
        MultiImageSelector.create(this)
                .showCamera(true) // 是否显示相机. 默认为显示
                .count(8) // 最大选择图片数量, 默认为9. 只有在选择模式为多选时有效
//        .single() // 单选模式
                .multi() // 多选模式, 默认模式;
                .origin(listPhoto) // 默认已选择图片. 只有在选择模式为多选时有效
                .start(this, REQUEST_IMAGE);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position == 0) {
            getPermissions();
        } else if (position < listPhoto.size() + 1) {
            List<ImageInfo> imageInfo = new ArrayList<>();
            for (int i = 0; i < listPhoto.size(); i++) {
                ImageInfo info = new ImageInfo();
                if (i < listPhoto.size()) {
                    info.bigImageUrl = listPhoto.get(i);
                    info.thumbnailUrl = listPhoto.get(i);
                }
                //拿到view的位置
                View imageView;
                imageView = gridview.getChildAt(position);
                info.imageViewWidth = imageView.getWidth();
                info.imageViewHeight = imageView.getHeight();
                int[] points = new int[2];
                imageView.getLocationInWindow(points);
                info.imageViewX = points[0];
                info.imageViewY = points[1] - getStatusBarHeight();
                imageInfo.add(info);
            }
            // 启动预览.
            Intent intent = new Intent(this, ImagePreviewActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(ImagePreviewActivity.IMAGE_INFO, (Serializable) imageInfo);
            bundle.putInt(ImagePreviewActivity.CURRENT_ITEM, position - 1);
            intent.putExtras(bundle);
            startActivity(intent);
            overridePendingTransition(0, 0);
        } else {
            Intent intent = new Intent(this, PhotoViewActivity.class);
            intent.putExtra("id", urllI);
            startActivity(intent);
        }
    }

    @Override
    public void onItemClick(int position) {
        listPhoto.remove(position);
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE) {
            // 获取返回的图片列表(存放的是图片路径)
            if (data != null) {
                //返回的图片路径
                listPhoto = data.getStringArrayListExtra(MultiImageSelector.EXTRA_RESULT);
                adapter.setData(listPhoto);
            }
        }
    }

    @Override
    public void onClik(int position) {
        proveYype = position;
        txtChooseProve.setText(choiceBeanList.get(position).name);
        switch (position) {
            case 0:
                urllI = R.mipmap.zhengduan;
                break;
            case 1:
                urllI = R.mipmap.ruyuan;
                break;
            case 2:
                urllI = R.mipmap.chuyuan;
                break;
            case 3:
                urllI = R.mipmap.bingqing;
                break;
        }
        adapter.setUrlLi(urllI);
    }

    /**
     * 网络请求返回
     *
     * @param mGsonBaseProtocol
     */
    @Override
    public void success(SupplyDiseaseProtocol mGsonBaseProtocol) {
        FileUtils.clearImage();
        dialog.dismiss();
        if (intentType == 0) {
            Intent intent = new Intent(this, ReplenishmentDiseaseInformationTwoActivity.class);
            intent.putExtra("info_id", infoID);
            intent.putExtra("supply_id", mGsonBaseProtocol.getData().getSupply_id());
            startActivity(intent);
        }
        finish();
        EventBus.getDefault().post(new BaseEventBean<>(Constants.TYPE_1, new SupplyDiseaseBean(1, mGsonBaseProtocol.getData().getSupply_id())));
    }

    @Override
    public void error(String mErrorProtocal) {
        FileUtils.clearImage();
        dialog.dismiss();
    }

    @Override
    public void notNet() {
        FileUtils.clearImage();
        dialog.dismiss();
    }

    @Override
    public void requestError() {
        FileUtils.clearImage();
        dialog.dismiss();
    }
}
